"""回合制战斗游戏完整演示"""

import json
from game.game_manager import GameManager
from models.character import Character, CharacterType


def print_header(title):
    """打印标题"""
    print("\n" + "=" * 60)
    print(f" {title} ")
    print("=" * 60)


def demo_game_features():
    """演示游戏功能"""
    print_header("回合制战斗游戏功能演示")
    
    game_manager = GameManager()
    
    # 1. 显示技能系统
    print_header("1. 技能系统")
    skills = game_manager.get_available_skills()
    for skill_id, skill in skills.items():
        print(f"• {skill['name']} ({skill_id})")
        print(f"  类型: {skill['type']} | 目标: {skill['target_type']} | 威力: {skill['base_value']}")
        print(f"  描述: {skill['description']}")
        print()
    
    # 2. 创建自定义角色
    print_header("2. 角色系统演示")
    
    # 创建强力角色进行快速战斗
    # 我方角色放置在下方区域 (y=3-5)
    player_data = [
        {
            "name": "龙骑士", "hp": 200, "attack": 40, "defense": 20, "speed": 15, 
            "hit_rate": 90, "dodge_rate": 15, "crit_rate": 20, "crit_damage": 160,
            "x": 0, "y": 3
        },
        {
            "name": "大法师", "hp": 150, "attack": 50, "defense": 10, "speed": 25,
            "hit_rate": 95, "dodge_rate": 20, "crit_rate": 25, "crit_damage": 200,
            "x": 1, "y": 4
        }
    ]
    
    # 敌方角色放置在上方区域 (y=0-2)
    enemy_data = [
        {
            "name": "魔王", "hp": 250, "attack": 35, "defense": 25, "speed": 20,
            "hit_rate": 85, "dodge_rate": 25, "crit_rate": 15, "crit_damage": 180,
            "x": 1, "y": 1
        }
    ]
    
    print("玩家方角色:")
    for char in player_data:
        print(f"• {char['name']} - HP:{char['hp']} ATK:{char['attack']} DEF:{char['defense']} SPD:{char['speed']}")
    
    print("\n敌方角色:")
    for char in enemy_data:
        print(f"• {char['name']} - HP:{char['hp']} ATK:{char['attack']} DEF:{char['defense']} SPD:{char['speed']}")
    
    # 3. 战场布局演示
    print_header("3. 战场布局 (4x6网格)")
    print("战场坐标系统:")
    print("  0   1   2   3  (X轴)")
    print("0 .   .   .   .  ← 敌方B队区域")
    print("1 .   魔  .   .  ← 敌方B队区域")
    print("2 .   .   .   .  ← 敌方B队区域")
    print("3 龙  .   .   .  ← 我方A队区域")
    print("4 .   法  .   .  ← 我方A队区域")
    print("5 .   .   .   .  ← 我方A队区域 (Y轴)")
    print("\n• 龙骑士在(0,3) - 我方前排坦克位置")
    print("• 大法师在(1,4) - 我方后排输出位置")
    print("• 魔王在(1,1) - 敌方核心位置")
    
    # 4. 执行战斗
    print_header("4. 战斗执行")
    print("正在创建战斗...")
    
    battle_id = game_manager.create_custom_battle(player_data, enemy_data)
    print(f"战斗ID: {battle_id}")
    
    # 显示初始状态
    state = game_manager.get_battle_state()
    print("\n初始战斗状态:")
    print(f"状态: {state['status']} | 回合: {state['current_round']}")
    
    print("\n开始自动战斗...")
    battle_result = game_manager.run_auto_battle(battle_id)
    
    # 5. 战斗结果分析
    print_header("5. 战斗结果")
    print(f"战斗ID: {battle_result['battle_id']}")
    print(f"总回合数: {len(battle_result['rounds'])}")
    
    if battle_result.get('final_result'):
        final = battle_result['final_result']
        winner = "玩家方" if final['winner'] == 'player' else "敌方"
        print(f"获胜方: {winner}")
        
        print("\n最终角色状态:")
        print("玩家方:")
        for char in final['player_characters']:
            status = "存活" if char['is_alive'] else "阵亡"
            print(f"  • {char['name']}: {char['hp']} HP - {status}")
        
        print("敌方:")
        for char in final['enemy_characters']:
            status = "存活" if char['is_alive'] else "阵亡"
            print(f"  • {char['name']}: {char['hp']} HP - {status}")
    
    # 6. JSON输出演示
    print_header("6. JSON格式输出")
    
    # 保存完整结果
    result_filename = "demo_battle_result.json"
    with open(result_filename, 'w', encoding='utf-8') as f:
        json.dump(battle_result['final_result'], f, ensure_ascii=False, indent=2)
    
    print(f"完整战斗结果已保存到: {result_filename}")
    
    # 显示JSON结构概览
    print("\nJSON结果结构:")
    print("{")    
    print('  "battle_id": "战斗唯一标识",')
    print('  "status": "finished",')
    print('  "winner": "player/enemy",')
    print('  "total_rounds": 回合数,')
    print('  "player_characters": [角色状态列表],')
    print('  "enemy_characters": [角色状态列表],')
    print('  "battlefield": {战场布局信息},')
    print('  "battle_log": [详细战斗记录]')
    print("}")
    
    # 7. 技能效果演示
    print_header("7. 技能效果统计")
    
    damage_dealt = 0
    healing_done = 0
    
    for round_data in battle_result['rounds']:
        for action in round_data['actions']:
            for effect in action['effects']:
                if effect['effect_type'] == 'damage':
                    damage_dealt += effect['value']
                elif effect['effect_type'] == 'heal':
                    healing_done += effect['value']
    
    print(f"总伤害输出: {damage_dealt}")
    print(f"总治疗量: {healing_done}")
    print(f"平均每回合伤害: {damage_dealt / len(battle_result['rounds']):.1f}")
    
    print_header("演示完成")
    print("✅ 角色系统 - 支持自定义属性和类型")
    print("✅ 战场系统 - 4x3网格布局和位置管理")
    print("✅ 技能系统 - 单体/范围 伤害/治疗技能")
    print("✅ 战斗引擎 - 回合制战斗逻辑")
    print("✅ JSON输出 - 完整的战斗结果数据")
    print("\n项目文件结构:")
    print("battlegame/")
    print("├── models/          # 数据模型")
    print("│   ├── character.py  # 角色模型")
    print("│   ├── battlefield.py# 战场模型")
    print("│   ├── skill.py     # 技能模型")
    print("│   └── battle.py    # 战斗模型")
    print("├── game/            # 游戏逻辑")
    print("│   ├── battle_engine.py # 战斗引擎")
    print("│   └── game_manager.py  # 游戏管理器")
    print("├── utils/           # 工具模块")
    print("│   └── json_encoder.py  # JSON编码器")
    print("└── main.py          # 主程序")


if __name__ == "__main__":
    demo_game_features()